from django.contrib.auth.decorators import login_required
from django.forms.models import modelformset_factory
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django.utils.translation import ugettext as _
from skran import models
from skran.models import Project, Sprint, History, TimeLog, PLANNING_TASK, \
    Milestone
from skran.sprint.planning1.forms import HistoryForm
import datetime
import logging


logging.info('Creating logger') 
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)

###################################################################################################
#                                         CREATE SPRINT
###################################################################################################

@login_required
def create_sprint(request, id_project):
    
    LOG.debug("User:" + request.user.username + " create new sprint for project " + id_project)
    
    #TODO:Ver esquema de seguranca    
    project = Project.objects.get(pk=id_project)
    
    milestone = Milestone()
    milestone.project = project
    milestone.name = "Milestone 0"
    milestone.save()
        
    sprint = Sprint()
    sprint.name = _('Sprint') 
    sprint.goal = _('Write Goal')
    
    sprint.created_by = request.user.username
    sprint.updated_by = request.user.username
    sprint.create_date = datetime.datetime.now()
    sprint.last_update = datetime.datetime.now()
    
    sprint.project = project
    sprint.milestone = milestone 
    sprint.number = Sprint.objects.filter(project=sprint.project).count()
     
    sprint.dailly = datetime.datetime.now()
    sprint.review = datetime.datetime.now()
    sprint.planning_1 = datetime.datetime.now()
    sprint.planning_2 = datetime.datetime.now()
    sprint.retrospective = datetime.datetime.now()
    
    #Creat new log time
    time_log = TimeLog()
    time_log.paused = 0
    time_log.status = models.STOPPED
            
    time_log.created_by = request.user.username
    time_log.updated_by = request.user.username
    time_log.create_date = datetime.datetime.now()
    time_log.last_update = datetime.datetime.now()

    time_log.save()
    
    sprint.planning1_time = time_log
    
    #Log time for planning 2
    time_log = TimeLog()
    time_log.paused = 0
    time_log.status = models.STOPPED
            
    time_log.created_by = request.user.username
    time_log.updated_by = request.user.username
    time_log.create_date = datetime.datetime.now()
    time_log.last_update = datetime.datetime.now()

    time_log.save()
    
    sprint.planning2_time = time_log
    sprint.save()
    
    return HttpResponseRedirect(sprint.edit_sprint_url())
    
###################################################################################################
#                                         EDIT SPRINT
###################################################################################################

@login_required
def create_history(request, id_sprint):
    
    LOG.debug("Creating history - " + id_sprint)
    
    if request.method == 'POST':
        history_form = HistoryForm(request.POST)
        
        if history_form.is_valid():
            sprint = Sprint.objects.get(pk=id_sprint)
            history_form.save(request.user, sprint.project, sprint)
                    
    #Rerender edit function
    histories_formset, release_formset, sprint, planning_time = edit_get(request, id_sprint)
                        
    return render_to_response('create-sprint.html', locals(), context_instance=RequestContext(request))        
        
@login_required
def edit_sprint(request, id_sprint):

    LOG.debug("Edit sprint - " + id_sprint)

    # Form to create new histories
    history_form = HistoryForm()

    if request.method == 'POST':
        histories_formset, release_formset, sprint, planning_time = edit_sprint_post(request, id_sprint)        
    elif request.method == 'GET':
        histories_formset, release_formset, sprint, planning_time = edit_get(request, id_sprint)
        
    return render_to_response('create-sprint.html', locals(), context_instance=RequestContext(request))


def edit_sprint_post(request, id_sprint):
    """
        Post function to create task in sprint
    
        @param request - django request 
        @param id_project
    """
    LOG.debug("POST to create history in sprint for project %s ", id_sprint)
    
    sprint_histories = History.objects.filter(sprint=id_sprint).order_by('priority', '-create_date')
    
    HistoriesFormSet = modelformset_factory(History, extra=0, can_order=True, form=HistoryForm)
    histories_formset = HistoriesFormSet(request.POST, queryset=sprint_histories)
    
    for form in histories_formset.forms:
        if form.is_valid():
            #TODO:Checar se o botao clicado foi para deletar
            if form.cleaned_data['check']:
                if 'delete-history' in request.POST:
                    form.delete()
                if 'store-history' in request.POST:
                    sprint = Sprint.objects.get(pk=id_sprint)
                    form.save(request.user, sprint.project, None)
            else:
                sprint = Sprint.objects.get(pk=id_sprint)
                form.save(request.user, sprint.project, sprint)

    return edit_get(request, id_sprint)

@login_required
def planning1_status(request, id_sprint):
    """
        Function to start sprint
        
        @param request: django request
        @param id_sprint: sprint id
        @param status: change status  
    """
    
    if request.method == 'POST':
        sprint = Sprint.objects.get(pk=id_sprint)
        
        if "start-planning" in request.POST:
            sprint.planning1_time.started = datetime.datetime.now()
            sprint.planning1_time.status = models.STARTED
                
            sprint.planning1_time.updated_by = request.user.username
            sprint.planning1_time.last_update = datetime.datetime.now()    
                
            sprint.planning1_time.save()
                            
        elif "pause-planning" in request.POST:
            sprint.planning1_time.stoped = datetime.datetime.now()
            sprint.planning1_time.status = models.PAUSED
            
            sprint.planning1_time.updated_by = request.user.username
            sprint.planning1_time.last_update = datetime.datetime.now()

            sprint.planning1_time.save()
            
        elif "continue-planning" in request.POST:
            sprint.planning1_time.status = models.STARTED
            
            stoped = sprint.planning1_time.stoped
            paused = sprint.planning1_time.paused
            if not paused:
                paused = 0
            diff = datetime.datetime.now() - stoped
            sprint.planning1_time.paused = paused + diff.seconds
           
            sprint.planning1_time.updated_by = request.user.username
            sprint.planning1_time.last_update = datetime.datetime.now()

            sprint.planning1_time.save()
        elif "stop-planning" in request.POST:
            time_log = sprint.planning1_time
            time_log.stoped = datetime.datetime.now()
            time_log.status = models.STOPPED
            time_log.save()
            
            sprint.planning1_time = time_log
            sprint.sprint_status = PLANNING_TASK
            sprint.save() 
            
            return HttpResponseRedirect(sprint.sprint_url_status())

        time = sprint.planning1_time
        planning_time = calculate_planning_time(sprint)
        
        return render_to_response('planning-status.html', locals(), context_instance=RequestContext(request))


def calculate_planning_time(sprint):

    """
        Calculate sprint time
    """
    if not sprint.planning1_time.started:
        return datetime.timedelta(seconds=0)
    
    if sprint.planning1_time.status == models.STOPPED or sprint.planning1_time.status == models.PAUSED:
        return (sprint.planning1_time.stoped - sprint.planning1_time.started) - datetime.timedelta(seconds=sprint.planning1_time.paused)
    else:
        return (datetime.datetime.now() - sprint.planning1_time.started) - datetime.timedelta(seconds=sprint.planning1_time.paused)
        
        
    
###################################################################################################
#                                         EDIT RELEASE
###################################################################################################

@login_required
def edit_release(request, id_sprint):
    
    LOG.debug("Edit release - " + id_sprint)

    # Form to create new histories
    history_form = HistoryForm()

    if request.method == 'POST':
        histories_formset, release_formset, sprint, planning_time = edit_release_post(request, id_sprint)        
    elif request.method == 'GET':
        histories_formset, release_formset, sprint, planning_time = edit_get(request, id_sprint)
      
    return render_to_response('create-sprint.html', locals(), context_instance=RequestContext(request))


def edit_release_post(request, id_sprint):
    """
        Post function to edit histories in release backlog
    
        @param request - django request 
        @param id_sprint
    """
    LOG.debug("POST to edit histories in release in sprint %s ", id_sprint)
    
    release_histories = History.objects.filter(sprint=None).order_by('priority', '-create_date')
    
    HistoriesFormSet = modelformset_factory(History, extra=0, can_order=True, form=HistoryForm)
    release_formset = HistoriesFormSet(request.POST, queryset=release_histories)
    
    for form in release_formset.forms:
        if form.is_valid():
            #TODO:Checar se o botao clicado foi para deletar
            if form.cleaned_data['check']:
                if 'delete-history' in request.POST:
                    form.delete()
                if 'promote-history' in request.POST:
                    sprint = Sprint.objects.get(pk=id_sprint)
                    form.save(request.user, sprint.project, sprint)
            else:
                sprint = Sprint.objects.get(pk=id_sprint)
                form.save(request.user, sprint.project, None)

    return edit_get(request, id_sprint)

def edit_get(request, id_sprint):

    #Sprint informations
    sprint = Sprint.objects.get(pk=id_sprint)
    
    # Form for sprint history
    sprint_histories = History.objects.filter(sprint=id_sprint).order_by('priority', '-create_date')
    HistoriesFormSet = modelformset_factory(History, extra=0, can_order=True, form=HistoryForm)
    histories_formset = HistoriesFormSet(queryset=sprint_histories)
    
    # Form for release history
    release_histories = History.objects.filter(sprint=None).order_by('priority', '-create_date')
    ReleaseFormSet = modelformset_factory(History, extra=0, can_order=True, form=HistoryForm)
    release_formset = ReleaseFormSet(queryset=release_histories)
    planning_time = calculate_planning_time(sprint)
    
    return histories_formset, release_formset, sprint, planning_time

###################################################################################################
#                                   EDIT HISTORY
###################################################################################################

@login_required
def edit_history(request, id_history):
    """
        Edit history using ajax
        
        @param request - django request 
        @param id_history to be edit
    """
    
    if request.method == 'POST':
        history_edit_form = HistoryForm(request)
        
        if history_edit_form.is_valid():
            pass
    elif request.method == 'GET':
        history = History.objects.get(pk=id_history)       
        history_edit_form = HistoryForm(history) 
    
    render_to_response('create-sprint.html', locals(), context_instance=RequestContext(request))
    
